package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.node.impl.ActionNode;
import com.sparrow.common.map.Position;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.impl.Monster;
import com.study.example.gameserver.module.scene.service.SceneService;
import com.study.example.gameserver.module.player.entity.Player;

import java.util.List;

import static com.sparrow.common.aoi.util.MapUtil.toPositionList;
import static com.sparrow.common.aoi.util.MapUtil.worldToGrid;

/**
 * 行为节点：追击敌人
 */
public class ChaseEnemy extends ActionNode {

    /** 每隔多少毫秒重新计算追击路径 */
    private static final long PATH_UPDATE_INTERVAL = 1000L;

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        Monster monster = context.getOwner();
        if (monster == null || monster.getTargetId() == 0L) {
            return BTNodeStatus.FAILURE;
        }

        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null) {
            return BTNodeStatus.FAILURE;
        }

        Player target = findTarget(sceneMap, monster);
        if (target == null || target.getPos() == null) {
            return BTNodeStatus.FAILURE;
        }
        context.put("ChaseTarget", target);
        // 检查是否需要重新计算路径
        Long lastPathTime = context.getOr("LastChasePathTime", Long.class, 0L);
        if (now - lastPathTime < PATH_UPDATE_INTERVAL) {
            return BTNodeStatus.SUCCESS; // 使用旧路径
        }

        // 世界坐标 → 格子坐标
        int[] start = worldToGrid(monster.getPos());
        int[] end = worldToGrid(target.getPos());
        if (start == null || end == null) {
            return BTNodeStatus.FAILURE;
        }

        // 调用寻路算法
        List<int[]> path = monster.getAStar()
                .findPath(sceneMap.getMapData().getWalkable(), start, end);
        if (path == null || path.isEmpty()) {
            return BTNodeStatus.FAILURE;
        }

        // 格子路径 → 世界坐标路径
        List<Position> roads = toPositionList(path);
        monster.setRoads(roads);
        monster.setRoadIndex(1);
        monster.updateAngle();
        // 更新上下文缓存
        context.put("LastChasePathTime", now);
        context.put("LastTargetPos", target.getPos());

        // 同步怪物状态（发给客户端）
        SceneService sceneService = context.get("SceneMapService", SceneService.class);
        if (sceneService != null) {
            sceneService.sendMonsterInfo(monster);
        }

        return BTNodeStatus.SUCCESS;
    }

    @Override
    public void initParams(String name, String value) {
        // 可扩展用于配置 interval 或追击策略
    }

    private Player findTarget(SceneMap sceneMap, Monster monster) {
        long targetId = monster.getTargetId();
        if (targetId <= 0) {
            return null;
        }
        return (Player) sceneMap.getPlayers().get(targetId);
    }
}
